<?php

namespace App\Services\Accompany;

use App\Exceptions\BasicException;
use App\Models\MainDB\Accompany\AccompanyCouponUser;
use App\Models\MainDB\Accompany\AccompanyOrder;
use App\Models\MainDB\Accompany\AccompanyOrderRefund;
use App\Repositories\Accompany\AccompanyOrderLogRepository;
use App\Repositories\Accompany\AccompanyOrderRefundLogRepository;
use App\Repositories\Accompany\AccompanyOrderRefundRepository;
use App\Repositories\WalletRepository;
use Exception;
use Illuminate\Support\Facades\DB;

class AccompanyOrderRefundService
{
    /**
     * 用户发起退款
     * @param $userId
     * @param $orderId
     * @param $reason
     * @param $picture
     * @param $description
     * @return void
     * @throws BasicException
     * @throws Exception
     */
    public function refund($userId, $orderId, $reason, $picture, $description)
    {
        $accompanyOrder = AccompanyOrder::query()->where(['user_id' => $userId, 'id' => $orderId])->first();
        if (empty($accompanyOrder)) {
            throw new BasicException(-1, '订单不存在');
        }
        if ($accompanyOrder['status'] == 2 && $accompanyOrder['accomplish_at'] < date('Y-m-d H:i:s',time() -24*3600)){
            throw new BasicException(-1, '此订单已超过24小时');
        }
        $accompanyOrderRefund = AccompanyOrderRefund::query()->where(['order_id' => $orderId])->first();
        if ($accompanyOrderRefund) {
            throw new BasicException(-1, '此订单已存在售后');
        }
        $picture = array_filter($picture);
        if (count($picture) > 3) {
            throw new BasicException(-1, '补充图片最多三张');
        }
        DB::beginTransaction();
        try {
            $orderRefundId = AccompanyOrderRefundRepository::getInstance()->save($orderId, $reason, implode(',', $picture), $description);
            $content = sprintf('用户%s发起了退款', $userId);
            AccompanyOrderRefundLogRepository::getInstance()->save($orderId, $orderRefundId, $content);
            // 维护订单表售后表售后状态
            // AccompanyOrder::query()->where(['id' => $orderId])->update(['status' => 0, 'refund_id' => $orderRefundId]);
            AccompanyOrder::query()->where(['id' => $orderId])->update(['refund_id' => $orderRefundId
                , 'create_refund_time'=>date('Y-m-d H:i:s', time())]);
            DB::commit();
            return $orderRefundId;
        } catch (Exception $e) {
            DB::rollBack();
            throw new BasicException($e->getCode(), $e->getMessage());
        }
    }


    /**
     * 主播同意退款
     * @param $userId
     * @param $orderId
     * @return bool
     * @throws BasicException
     * @throws Exception
     */
    public function refundAgree($userId, $orderId,$type = 0)
    {
        $accompanyOrder = AccompanyOrder::query()->where(['anchor_id' => $userId, 'id' => $orderId])->first();
        if (empty($accompanyOrder)) {
            throw new BasicException(-1, '订单不存在');
        }
        if ($accompanyOrder->status != 1 && $accompanyOrder->status != 2) { // 正在进行中的订单才可以申请退款
            throw new BasicException(-1, '订单不可退');
        }
        $orderRefund = AccompanyOrderRefund::query()->where(['order_id' => $orderId])->first();
        if (empty($orderRefund)) {
            throw new BasicException(-1, '售后订单不存在');
        }
        DB::beginTransaction();
        try {
            $price = $accompanyOrder->total_price;
            $desc    = "达人同意陪玩退款";
            if ($type == 1) {
                $desc = "超时退款";
            }
            WalletRepository::getInstance()->accompanyRefundAgree($accompanyOrder->user_id, $price, (int)$accompanyOrder->id,$desc);
            // 退还
            AccompanyOrderRefund::query()->where(['order_id' => $orderId])->update(['status' => 5]);
            $refundStatus = 1;
            if ($type == 1) {
                $refundStatus = 3;
            }
            AccompanyOrder::query()->where(['id' => $orderId])->update(['status' => -2, 'refund_status' => $refundStatus]);
            // 订单是否使用优惠券 - 退还优惠券
            if ($accompanyOrder->coupon_id != 0) {
                $accompanyCouponUser = AccompanyCouponUser::query()->where(['id' => $accompanyOrder->coupon_id, 'user_id' => $accompanyOrder->user_id])->first();
                if ($accompanyCouponUser) {
                    $accompanyCouponUser->status = 0;
                    $accompanyCouponUser->refund = $accompanyCouponUser->refund + 1;
                    $accompanyCouponUser->save();
                }
            }
            $content = sprintf('达人%s同意陪玩退款', $userId);
            if ($type ==1){
                $content = '超时退款';
            }
            AccompanyOrderRefundLogRepository::getInstance()->save($orderId, $orderRefund->id, $content);

            AccompanyOrderLogRepository::getInstance()->save($orderId, '2', $desc, $userId);
            DB::commit();
            return true;
        } catch (Exception $e) {
            DB::rollBack();
            throw new BasicException($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 主播拒绝退款,发起申诉
     * @param $userId
     * @param $orderId
     * @param $reason
     * @param $picture
     * @return void
     * @throws BasicException
     * @throws Exception
     */
    public function complaint($userId, $orderId, $reason, $picture)
    {
        $accompanyOrder = AccompanyOrder::query()->where(['anchor_id' => $userId, 'id' => $orderId])->first();
        if (empty($accompanyOrder)) {
            throw new BasicException(-1, '订单不存在');
        }
        $accompanyOrderRefund = AccompanyOrderRefund::query()->where(['order_id' => $orderId])->first();
        $picture = array_filter($picture);
        if (count($picture) > 3) {
            throw new BasicException(-1, '补充图片最多三张');
        }
        $orderRefundId = $accompanyOrderRefund->id;
        DB::beginTransaction();
        try {
            // 维护订单表售后表售后状态
            AccompanyOrderRefund::query()->where(['order_id' => $orderId])->update([
                'status'         => 2,
                'anchor_reason'  => $reason,
                'anchor_picture' => implode(',', $picture),
            ]);
//            AccompanyOrder::query()->where(['id' => $orderId])->update(['status' => 0, 'refund_id' => $orderRefundId, 'refund_status' => -1]);
            AccompanyOrder::query()->where(['id' => $orderId])->update(['refund_id' => $orderRefundId, 'refund_status' => -1]);
            $content = sprintf('主播%s拒绝退款,发起申诉', $userId);
            AccompanyOrderRefundLogRepository::getInstance()->save($orderId, $orderRefundId, $content);
            DB::commit();
            return $orderRefundId;
        } catch (Exception $e) {
            DB::rollBack();
            throw new BasicException($e->getCode(), $e->getMessage());
        }
    }

}
